package com.chanyachting.emall.action.member;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.chanyachting.emall.domain.Member;
import com.chanyachting.emall.form.MemberForm;
import com.chanyachting.emall.service.MemberService;
import com.chanyachting.emall.serviceImpl.MemberServiceImpl;
import com.chanyachting.emall.util.RequestUtil;

public class MemberManagerAction extends DispatchAction {

	
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		MemberService ms=new MemberServiceImpl();
		
		List list=ms.getAllMember();
		
		new RequestUtil(request).setAttribute("memberList", list);
		
		return mapping.findForward("list");
	}
	
	
	
	public ActionForward show(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		int id=Integer.parseInt(new RequestUtil(request).getParameter("id", "0"));
		
		Member member=new Member(id);
		
		MemberService ms=new MemberServiceImpl();
		
		member=ms.getOneMember(member);
		
		new RequestUtil(request).setAttribute("member", member);
		
		return mapping.findForward("show");
	}
	
	
	
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		int id=Integer.parseInt(new RequestUtil(request).getParameter("id", "0"));
		
		Member member=new Member(id);
		
		if(request.getMethod().equals("POST")){
			
			MemberForm mform=(MemberForm)form;
			
			//如果验证成功
			if(mform.validate(mapping, request).isEmpty()){
				
				Member m=new Member();
				
				BeanUtils.copyProperties(m, mform);
				
				MemberService ms=new MemberServiceImpl();
				
				ms.updateMemberInfo(m);
				
				new RequestUtil(request).setSuccessMsg();
				
			}
			
		}
		
		//重新加载member对象
		MemberService ms=new MemberServiceImpl();
		
		member=ms.getOneMember(member);

		new RequestUtil(request).setAttribute("member", member);
		
		
		return mapping.findForward("update");
	}
	
	
	

}
